<template>
  <div class="container">
    <div class="login-form">
      <el-form :model="dataForm" :rules="dataFormRule" ref="dataForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="dataForm.username">

          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="dataForm.password">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import Cookie from 'js-cookie'
export default {
  name: "Login.vue",
  data() {
    return {
      dataForm: {
        username: '',
        password: '',
      },
      dataFormRule: {
        username: [{required: true, message: "请输入用户名", trigger: "blur"}],
        password: [{required: true, message: "请输入密码", trigger: "blur"}],
      }
    }
  },
  methods: {
    login() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        // 1：获取access token
        this.$http.post('/login', this.dataForm, {
          transformRequest:
              [function (data) {
                let ret = '';
                for (let i in data) {
                  ret += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&'
                }
                return ret;
              }],
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).then(({data: res}) => {
          if (res.code !== '200') {
            this.$message.error(res.msg)
            return
          }
          const userInfo = res.data.principal;
          Cookie.set('user',JSON.stringify(userInfo))
          this.$store.commit('login',userInfo)
          this.$router.replace({name: 'index'})
        }).catch(() => {
          this.$message.error('用户名或密码错误')
        })
      })
    }
  }
}
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
}

.login-form {
  width: 400px;
  top: 50%;
  left: 50%;
  position: absolute;
  transform: translate(-50%, -50%);
}
</style>
